package com.example.e_comm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取所有用户列表
     *
     * @return 用户列表
     */
    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    /**
     * 分页获取用户列表
     *
     * @param pageNum  页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @return 分页用户数据
     */
    @GetMapping("/listByPage")
    public IPage<User> listByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.page(new Page<>(pageNum, pageSize));
    }

    @GetMapping("/{userId}")
    public User getUserById(@PathVariable Long userId) {
        if(userService.getUsersById(userId)== null){
            throw new RuntimeException("用户不存在");
        }
        return userService.getById(userId);
    }
    /**
     * 创建用户
     *
     * @param user 用户对象
     * @return 是否创建成功
     */
    @PostMapping("/create")
    public boolean create(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.count(new QueryWrapper<User>().eq("username", user.getUsername())) > 0) {
            return false;
        }
        // 检查邮箱是否已存在
        if (userService.count(new QueryWrapper<User>().eq("email", user.getEmail())) > 0) {
            return false;
        }
        return userService.save(user);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return 是否更新成功
     */
    @PostMapping("/update")
    public boolean update(@RequestBody User user) {
        return userService.updateById(user);
    }

    /**
     * 删除用户（逻辑删除）
     *
     * @param user 用户对象
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    public boolean delete(@RequestBody User user) {
        return userService.removeById(user);
    }

    /**
     * 批量删除用户（逻辑删除）
     *
     * @param ids 用户ID列表
     * @return 是否删除成功
     */
    @PostMapping("/delete/ids")
    public boolean delete(@RequestBody List<Long> ids) {
        return userService.removeByIds(ids);
    }




    //用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try{
            boolean result = userService.register(user);
            if(result){
                return ResponseEntity.ok("注册成功");
            }else{
                return ResponseEntity.ok("注册失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    //用户登录信息
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username,@RequestParam String password) {
        try{
            String token = userService.login(username,password);
            Map<String,String> response = new HashMap<>();
            response.put("token",token);
            response.put("message","登录成功");
            return ResponseEntity.ok(response);
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    //当前用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        //(可选)添加日志,帮助调试
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息:{}",userService.getUserByToken(token));
        try {
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息:{}",userService.getUserByToken(clean));
            User user = userService.getUserByToken(clean);
            if(user != null){
                user.setPassword(null);//屏蔽password敏感数据
                return ResponseEntity.ok(user);
            }else {
                logger.warn("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token,或Token已过期");
            }
        }catch (Exception e){
            logger.error("请求错误：",e);
            return ResponseEntity.status(400).body("请求错误"+e.getMessage());
        }
    }
    //退出登录
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
        try{
            boolean result = userService.logout(token.replace("Bearer ", ""));//过滤token中的Bearer
            if(result){
                return ResponseEntity.ok("注销成功");
            }else{
                return ResponseEntity.ok("注销失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

